import React from 'react';
import {inject, observer} from 'mobx-react';
import { withRouter } from 'react-router-dom';
import classnames from 'classnames';
import {Bubble, Button, Tools, Modal, Toast, Icon } from 'weaver-mobile';
import { CKRichText, MapPage } from 'weaver-mobile-page';
import WeaUtils from '../../public/wea-utils';
const getLabel = Tools.getLabel;
const getCurrentPosition = MapPage.getCurrentPosition;
const alert = Modal.alert;
@withRouter
@inject('blogCommentStore')
@observer
export default class BlogNoteWrite extends React.Component {
    static defaultProps = {
        prefixCls: 'blog-comment-write'
    }
    constructor(props) {
        super(props);
        this.state = {
            locationading:false,
            noteLoading:false,
            positionLoading: false,
            position: '',
            address: '',
            positionError: false,
        }
    }

    componentWillMount() {
        const {blogCommentStore} = this.props;

        blogCommentStore.setRoutePath(this.props.location.pathname);
        blogCommentStore.setReplyConfig();
    }

    componentDidMount() {
        const { blogCommentStore: { writeReply } } = this.props;
        const store = this.getStore();
        const { setBlogText,getBlogBianQian} = store;

        getBlogBianQian({},(_param) => {
            writeReply.setData({richText: _param});
            setBlogText(_param);
        })
    }

    componentWillUnmount() {
        const store = this.getStore();
        store.clearBlogText();
    }

    getStore = () => {
        const {writeBlogStore, storeName} = this.props;
        return writeBlogStore[storeName] || writeBlogStore;
    }

    onBrowserChange = (key, datas) => {
        const { blogCommentStore: { writeReply } } = this.props;
        datas.map(v => {
            if(key === 'template'){
                const store = this.getStore();
                const { blogText} = store;
                if(blogText){
                    Modal.alert(getLabel(505615,'替换当前内容？'),'', [
                        { text: getLabel(31129, '取消') },
                        {
                            text: getLabel(33703, '确认'),
                            onPress: () => {
                                writeReply.setData({richText: `${v.name}`});
                            }
                        },
                    ])
                }else{
                    writeReply.setData({richText: `${v.name}`});
                }

            }else{
                writeReply.insertHtml(`<a href="javascript:void(0)" style="text-decoration:underline !important;" linkid="${v.id}" linktype="${key}" onclick="try{return openAppLink(this,${v.id});}catch(e){}">${v.name}</a>&nbsp;&nbsp;&nbsp;`);
            }
        });
    }

    //附件上传后事件
    onUploadChange = (key, datas) => {
        const { blogCommentStore: { writeReply } } = this.props;
        let str="";
        datas.map(item => {
            str = `<a href='javascript:void(0)' onclick='try{opendoc1(${item.fileid},this);return false;}catch(e){}' ondblclick='return false;' unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.filename}</a>
            &nbsp;<a href='javascript:void(0)'  onclick='try{downloads(${item.imagefileid},this,"${item.filename}");return false;}catch(e){}' unselectable='off' target='_blank' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>下载(${item.filesize})</a></br>`;
            writeReply.insertHtml(str);
        });
    }


    onAtChange = (datas) => {
        const { blogCommentStore: { writeReply } } = this.props;
        datas.map(v => {
            writeReply.insertHtml(`<span style="font-family:'Microsoft YaHei';font-size:12px"><span><a  uuuid="uuuid${v.id}uu" data-cke-saved-href="/spa/blog/static/index.html#/user/${v.id}"   href="/spa/blog/static/index.html#/user/${v.id}" contenteditable="false"  style="cursor:pointer;text-decoration:none !important;margin-right:8px;color:#2777c1!important;"  target="_blank">@${v.lastname}</a></span>&nbsp;</span>`)
        });
    }

    publishWeiboPermission =()=>{
        const { blogCommentStore: { getIsOneSubmitInfo } } = this.props;
        let _this = this;
        getIsOneSubmitInfo(result => {
          if (result.oneSubmit == "1" && result.submitCount>0) {
              Bubble.warning(getLabel(521404,'您已发布过今天的微博，不能再发布，已为您保存草稿。'), 3);
              this.saveNote();
          }else{
            if(result.oneSubmit == "1"&& result.submitCount==0){
              alert('',getLabel('521430',"当日微博仅能提交一次，确定要发布吗？"), [
                  { text: getLabel('31129','取消') , onPress: () => console.log('cancel') },
                  { text: getLabel('826','确定') , onPress: () => _this.blogSubmit() },
                ])
            }else{
              _this.blogSubmit();
            }
          }
        })
     }

    // 提交微博
    blogSubmit = () => {
        const { blogCommentStore: { writeReply } } = this.props;
        const { position, address } = this.state;
        let richContent = writeReply.getData().richText;
        if(!richContent){
            return;
        }


        const { history, match } = this.props;
        const store = this.getStore();
        const { saveOrUpdateBlog, replyComment,workdate} = store;
        let notedate = workdate;
        if(this.props.location.state=='bianqian'){
            notedate = WeaUtils.DateFormat(new Date(), 'yyyy-MM-dd');
        }
        this.setState({loading: true});
        Toast.loading(getLabel(513695,'发布中'), 30);
        const saveParams = position && {
            locationX: position[0],
            locationY: position[1],
            locationName: address,
        }
        saveOrUpdateBlog({
            content: richContent,
            workdate:  notedate,
            comefrom: 4,
            ...saveParams
        }, () => {
            Toast.hide();
            Toast.success(getLabel('33179','发布成功'), 1);
            if(this.props.location.state=='bianqian'){
                replyComment ? history.go(-1) : history.push('/userCenter')
            }else{
                replyComment ? history.go(-1) : history.push('/myBlog/blog')
            }

        })
    }



    // 保存便签
    saveNote = () => {
        const { blogCommentStore: { writeReply } } = this.props;
        let richContent = writeReply.getData().richText;
        if(!richContent){
            return;
        }

        const { history } = this.props;
        const store = this.getStore();
        const { saveOrUpdateBlogNote, workdate} = store;
        this.setState({noteLoading: true});
        Toast.loading(getLabel(505616,'保存中...'), 30);



        saveOrUpdateBlogNote({
            workdate: workdate ,
            content: richContent,
        }, () => {
            Toast.hide();
            Toast.success(getLabel(83551,'保存成功！'), 1);


            if(this.props.location.state=='bianqian'){
                history.push('/userCenter')
            }else{
                history.push('/myBlog/blog')
            }
        })
    }



    getLocaiton = () => {
        this.setState({ positionLoading: true });
        getCurrentPosition().then((result) => {
            this.setState({ positionLoading: false, position: result.position, address: result.address });
            if (!result.position) {
                this.setState({positionError: true})
            }
        });
    }



    render() {
        const { blogCommentStore: { writeReply,routePath }, prefixCls } = this.props;
        const store = this.getStore();
        const { blogText, setBlogText } =store;
        const { loading,noteLoading, position, address, positionLoading, positionError } = this.state;
        const replyProps = {
            onBrowserChange: this.onBrowserChange,
            onUploadChange: this.onUploadChange,
            onAtChange:this.onAtChange,
            leftConfig: [
                {type: 'voice'},
                {type: 'blog-biaoqing'},
                {type: 'blog-tupian', model: 2},
                {type: '@'},
                {type: 'tianjia'}
            ]
        }
        const config = {
            browserContextMenuOnCtrl: false,
            enableContextMenu: false,
        }

        const positionStr = position ? address : getLabel(22981,'位置');
        const positionName = classnames(`${prefixCls}-container-position-name`,
            {'active': address !== ''})
        return (
            <div className={prefixCls}>
                <div  id='writeTitle'  iswrite="note"  style={{"width": "100%","height": "20px","background-color": "#6d6d6d","text-align": "center","line-height": "20px","color": "white","font-family": "auto"}}>{getLabel(33304,'微博便签')}</div>
                <div className={`${prefixCls}-container`} style={{"margin-top":"20px"}}>
                    <CKRichText store={writeReply}
                                onChange={(val) => setBlogText(val)}
                                replyProps={replyProps}
                                config={config}
                    />
                    <div className={`${prefixCls}-container-position`}   onClick={this.getLocaiton}>
                        <Icon type={address !== '' ? 'position' : 'location'} size='xxs'/>
                        <span className={positionName} position={position}>{positionLoading ? getLabel(505617,'定位中...') : positionError ? getLabel(505618,'定位失败，请重试!') : positionStr}</span>
                    </div>
                </div>
                <Button
                    onClick={this.saveNote}
                    loading = {noteLoading}
                    style = {{width:"50%","position": "absolute","bottom": 0}}
                >{noteLoading ? getLabel(31116,'保存中'):getLabel(30986, '保存')}</Button>
                <Button type="primary"
                        disabled={blogText ? false : true}
                        onClick={this.publishWeiboPermission}
                        loading = {loading}
                        style = {{width:"50%","margin-left":" 50%","position": "absolute","bottom": 0}}
                >{loading ? getLabel(513695,'发布中') :getLabel(114,'发布') }</Button>
            </div>
        );
    }
}